package com.sikaryofficial.common.security.service;

import cn.hutool.core.text.CharSequenceUtil;
import com.sikaryofficial.common.core.constant.CacheConstants;
import com.sikaryofficial.common.core.constant.ChannelEnum;
import com.sikaryofficial.common.core.constant.DeviceIdEnum;
import com.sikaryofficial.common.core.constant.SecurityConstants;
import com.sikaryofficial.common.core.exception.ServiceException;
import com.sikaryofficial.common.core.utils.JwtUtils;
import com.sikaryofficial.common.core.utils.ServletUtils;
import com.sikaryofficial.common.core.utils.StringUtils;
import com.sikaryofficial.common.core.utils.ip.IpUtils;
import com.sikaryofficial.common.core.utils.uuid.IdUtils;
import com.sikaryofficial.common.redis.service.RedisService;
import com.sikaryofficial.common.security.utils.SecurityUtils;
import com.sikaryofficial.system.api.model.LoginUser;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.text.MessageFormat;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.TimeUnit;

/**
 * token验证处理
 *
 * @author ruoyi
 */
@Component
public class TokenService {
    protected static final long MILLIS_SECOND = 1000;
    protected static final long MILLIS_MINUTE = 60 * MILLIS_SECOND;
    private final static Long MILLIS_MINUTE_TEN = CacheConstants.REFRESH_TIME * MILLIS_MINUTE;
    private static final Logger log = LoggerFactory.getLogger(TokenService.class);
    private final static long expireTime = CacheConstants.EXPIRATION;
    private final static String ACCESS_TOKEN = CacheConstants.LOGIN_TOKEN_KEY;
    @Autowired
    private RedisService redisService;
    /**
     * 是否允许账户多终端同时登录（true允许 false不允许）
     */
    @Value("${hismk.token.soloLogin}")
    private boolean soloLogin;

    /**
     * 创建令牌
     */
    public Map<String, Object> createToken(LoginUser loginUser, String channel,String deviceId) {
        String token = IdUtils.fastUUID();
        Long userId = loginUser.getSysUser().getUserId();
        String userName = loginUser.getSysUser().getUserName();
        loginUser.setToken(token);
        loginUser.setUserid(userId);
        loginUser.setUsername(userName);
        loginUser.setIpaddr(IpUtils.getIpAddr());
        refreshToken(loginUser, channel, deviceId);

        // Jwt存储信息
        Map<String, Object> claimsMap = new HashMap<String, Object>();
        claimsMap.put(SecurityConstants.USER_KEY, token);
        claimsMap.put(SecurityConstants.DETAILS_USER_ID, userId);
        claimsMap.put(SecurityConstants.DETAILS_USERNAME, userName);

        // 接口返回信息
        Map<String, Object> rspMap = new HashMap<String, Object>();
        rspMap.put("access_token", JwtUtils.createToken(claimsMap));
        rspMap.put("expires_in", expireTime);
        return rspMap;
    }

    /**
     * 获取用户身份信息
     *
     * @return 用户信息
     */
    public LoginUser getLoginUser() {
        return getLoginUser(ServletUtils.getRequest());
    }

    /**
     * 设置用户身份信息
     */
    public void setLoginUser(LoginUser loginUser) {
        if (StringUtils.isNotNull(loginUser) && StringUtils.isNotEmpty(loginUser.getToken())) {
            refreshToken(loginUser, SecurityUtils.getChannel(),SecurityUtils.getDeviceId());
        }
    }

    /**
     * 获取用户身份信息
     *
     * @return 用户信息
     */
    public LoginUser getLoginUser(HttpServletRequest request) {
        // 获取请求携带的令牌
        String token = SecurityUtils.getToken(request);
        return getLoginUser(token);
    }

    /**
     * 获取用户身份信息
     *
     * @return 用户信息
     */
    public LoginUser getLoginUser(String token) {
        LoginUser user = null;
        try {
            if (StringUtils.isNotEmpty(token)) {
                String userKey = JwtUtils.getUserKey(token);
                user = redisService.getCacheObject(getTokenKey(userKey));
                return user;
            }
        } catch (Exception e) {
            log.error("获取用户信息异常'{}'", e.getMessage());
        }
        return user;
    }

    /**
     * 删除用户缓存信息
     */
    public void delLoginUser(String token) {
        if(Objects.isNull(getLoginUser(token)) || Objects.isNull(getLoginUser(token).getSysUser())){
            return;
        }
        Long userId = getLoginUser(token).getSysUser().getUserId();
        if (StringUtils.isNotEmpty(token)) {
            String userKey = JwtUtils.getUserKey(token);
            redisService.deleteObject(getTokenKey(userKey));
        }
        String channel = SecurityUtils.getChannel();
        String deviceId = SecurityUtils.getDeviceId();
        if(CharSequenceUtil.isBlank(channel)){
            channel = ServletUtils.getRequest().getHeader(SecurityConstants.CHANNEL_KEY);
        }
        if(CharSequenceUtil.isBlank(deviceId)){
            deviceId = ServletUtils.getRequest().getHeader(SecurityConstants.DEVICE_KEY);
        }
        log.info("logout,userIdKey:{},{}", userId, channel);
        if (soloLogin && Objects.nonNull(userId)) {
            String userIdKey = getUserIdAndChannelKey(userId, channel,deviceId);
            log.info("logout,userIdKey:{}", userIdKey);
            processUserTokenCache(userIdKey);
        }
    }

    /**
     * 删除用户缓存信息
     */
    public void delLoginUserCache(Long userId, String channel,String deviceId) {
        // 如果用户不允许多终端同时登录，清除缓存信息
        String userIdKey = MessageFormat.format(CacheConstants.LOGIN_USERID_KEY, String.valueOf(userId), channel,deviceId);
        log.info("login,userIdKey:{}", userIdKey);
        String userKey = redisService.getCacheObject(userIdKey);
        if (Objects.nonNull(userKey)) {
            redisService.deleteObject(userKey);
        }
        // 删除login_userid 与token
        if (soloLogin && StringUtils.isNotEmpty(userKey)) {
            log.info("login,userKey:{}", userKey);
            processUserTokenCache(userIdKey);
        }
    }

    /**
     * 删除用户缓存信息
     *
     * @param userIdKey : login_userid
     */
    private void processUserTokenCache(String userIdKey) {
        // login_userid 删除处理
        String loginTokensValue = redisService.getCacheObject(userIdKey);
        // 删除login_tokens
        if(CharSequenceUtil.isNotBlank(loginTokensValue)){
            redisService.deleteObject(loginTokensValue);
        }
        // 删除login_userid
        redisService.deleteObject(userIdKey);
    }

    /**
     * 验证令牌有效期，相差不足120分钟，自动刷新缓存
     *
     * @param loginUser
     */
    public void verifyToken(LoginUser loginUser, String channel,String deviceId) {
        long expireTime = loginUser.getExpireTime();
        long currentTime = System.currentTimeMillis();
        if (expireTime - currentTime <= MILLIS_MINUTE_TEN) {
            refreshToken(loginUser, channel,deviceId);
        }
    }

    /**
     * 刷新令牌有效期
     *
     * @param loginUser 登录信息
     */
    public void refreshToken(LoginUser loginUser, String channel,String deviceId) {
        loginUser.setLoginTime(System.currentTimeMillis());
        loginUser.setExpireTime(loginUser.getLoginTime() + expireTime * MILLIS_MINUTE);
        // 根据uuid将loginUser缓存
        String userKey = getTokenKey(loginUser.getToken());
        redisService.setCacheObject(userKey, loginUser, expireTime, TimeUnit.MINUTES);
        if (soloLogin) {
            // 缓存用户唯一标识，防止同一帐号，同时登录
            String userIdKey = getUserIdAndChannelKey(loginUser.getSysUser().getUserId(), channel,deviceId);
            // 不设置过期时间，永不过期
            redisService.setCacheObject(userIdKey, userKey);
        }
    }

    private String getTokenKey(String token) {
        /**
         * user的 token，隐藏在 redis 中
         */
        return ACCESS_TOKEN + token;
    }

    /**
     * 获取用户唯一标识
     *
     * @param userId  用户ID
     * @param channel 登录端渠道：mobile-移动端; pc-pc端
     * @return 用户唯一标识
     */
    private String getUserIdAndChannelKey(Long userId, String channel, String deviceId) {
        if (Objects.isNull(DeviceIdEnum.getNameByCode(deviceId))) {
            log.error("deviceId value is error.");
            throw new ServiceException("deviceId value is error.");
        }
        if (Objects.isNull(ChannelEnum.getNameByCode(channel))) {
            log.error("channel value is error.");
            throw new ServiceException("channel value is error.");
        }
        return MessageFormat.format(CacheConstants.LOGIN_USERID_KEY, String.valueOf(userId), channel, deviceId);
    }
}